/**
 * @Description: ajax
 * @author bev
 * @date 2019/9/30
 * @time 16:21
 */

import { baseUrl } from "../api/url.config";
import user from "../api/user";
import course from "../api/course";
import { Toast } from "./modal";
import { ReLaunch } from "./router";

/**
 * @function ajax
 * @param url
 * @param data
 * @param method
 * @param loading
 * @returns {Promise<unknown>}
 */

export const ajax = ({ url, data = {}, method = "POST" }) => {
  // console.log("ajax-query", data);
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + url,
      data,
      method,
      success(res) {
        console.log("ajax-res", res.data);
        const { code, message: title } = res.data;
        uni.hideLoading();
        uni.hideToast();
        switch (code) {
          case 1:
            resolve(res.data);
            break;
          case 0:
            Toast({ title });
            break;
          case 2:
            // Toast({
            //   title: "用户需要重新登陆",
            //   success() {
            //     setTimeout(() => {
            ReLaunch({ url: "/pages/login/auth/auth" });
          // }, 1500);
          // }
          // });
        }
      },
      fail() {
        Toast({ title: "网络错误" });

        reject("ajax fail");
      }
    });
  });
};

const RequestConfig = {
  user,
  course
};

let Request = {};

Object.entries(RequestConfig).forEach(([Name, Options]) => {
  const obj = { [Name]: {} };
  Object.entries(Options).forEach(([name, { url, method }]) => {
    obj[Name][name] = data =>
      ajax({
        url,
        method,
        data
      });
  });
  Request = { ...Request, ...obj };
});

export default Request;
